/*
 * @(#)SnmpConnectCollector
 *
 * Copyright 2001-2005 友联创新科技
 * 
 */
package com.sinodata.bsm.cicp.collector.net;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.common.vo.ResPropertyValue;
import com.sinodata.bsm.common.vo.ResPropertyValue.PropValue;
import com.union.net.snmp.SnmpGet;

/**
 * SnmpConnectCollector.java
 * <p>
 * Snmp可用性采集程序
 *
 * @author 李祥军 lixj@uni-mon.com
 * @version 1.0 
 * @Date 2010-6-25
 */
public class SnmpConnectCollector extends Collector {
    static Logger logger = Logger.getLogger(SnmpConnectCollector.class);
    static String[] ParamMeta = { "共同体", "重试次数" };
    static String[] PropMeta = { "SNMP状态" };

    @Override
    public List<ResPropertyValue> collect(String ip) {
        int retry = NumberUtils.toInt(getParamMap().get("重试次数"), 1);
        PropValue propValue = null;
        for (int i = 0; i < retry && propValue == null; i++) {
            propValue = testConnect(ip);
        }
        propValue = propValue == null ? ResPropertyValue.createPropValue("不可用", PropMeta[0]) : propValue;
        ResPropertyValue propertyValueX = new ResPropertyValue();
        propertyValueX.setValues(propValue);
        return Arrays.asList(propertyValueX);

    }

    public PropValue testConnect(String ip) {
        SnmpGet snmpGet = null;
        try {
            snmpGet = new SnmpGet(ip);
            snmpGet.setCommunity(getParamMap().get("共同体"));
            String value = snmpGet.getSingle("1.3.6.1.2.1.1.1.0");
            if (value != null)
                return ResPropertyValue.createPropValue("正常", PropMeta[0]);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (snmpGet != null)
                snmpGet.close();
        }
        return null;
    }

    @Override
    public String[] getParamMeta() {
        return ParamMeta;
    }

    @Override
    public String[] getPropMeta() {
        return PropMeta;
    }

}
